package cn.jingdalei.org.service.impl;

import cn.jingdalei.basic.service.IBaseService;
import cn.jingdalei.basic.service.impl.BaseServiceImpl;
import cn.jingdalei.basic.util.PageList;
import cn.jingdalei.org.domain.Department;
import cn.jingdalei.org.mapper.DepartmentMapper;
import cn.jingdalei.org.query.DepartmentQuery;
import cn.jingdalei.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
// 事物管理  当前类只读，有事物就支持没有就不管
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    // 1. 基础的CRUD通过继承实现  先继承公共的 再实现扩展的

    // 2. 扩展的功能自己单独写
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    //默认值(readOnly = false,propagation = Propagation.REQUIRED)
    @Transactional
    public void add(Department department) {
        departmentMapper.save(department); //这里必须返回自增id
        this.update(department);
    }

    @Override
    @Transactional
    public void update(Department department) {
        // 封装dirPath    回显上级部门树
        String dirPath = "";
        if (department.getParent() == null || department.getParent().getId()==null) { // 1. 新增顶级部门
            dirPath = "/"+department.getId();
        } else {  // 2. 修改非顶级部门 时将非顶级部门修改为顶级部门会报空指针
            // 获取上级部门
            Department parentDept = departmentMapper.loadById(department.getParent().getId());
            dirPath = parentDept.getDirPath()+"/"+department.getId();
        }
        department.setDirPath(dirPath);
        departmentMapper.update(department);
    }

    @Override
    public List<Department> deptTree() {
        return departmentMapper.deptTree();
    }
}
